package com.lut.edu.apm.commodityCenter.conteroller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lut.edu.apm.commodityCenter.pojo.CommodityLibrary;
import com.lut.edu.apm.commodityCenter.pojo.CommodityOrder;
import com.lut.edu.apm.commodityCenter.service.CommodityLibraryService;
import com.lut.edu.apm.commodityCenter.service.CommodityOrderService;
import com.lut.edu.apm.commodityCenter.service.ProductInquiry;
import com.lut.edu.apm.payCenter.services.OrderDetailService;
import io.lettuce.core.dynamic.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
 * 商品查询
 *
 * @author Zhao Suzhen
 * @date `2024/4/13`
 */
@Controller
@RequestMapping("/commodity")
public class CommodityController {

    private final Logger logger = LoggerFactory.getLogger(CommodityController.class);

    @Autowired
    ProductInquiry productInquiry;

    @Autowired
    CommodityOrderService commodityOrderService;

    @Autowired
    OrderDetailService orderDetailService;

    /**
     * 扫码查询商品(购买)
     *
     * @param codeNumber 商品码
     * @return
     */
    @GetMapping("queryProduct")
    @ResponseBody
    public String queryProduct(@RequestParam("codeNumber") String codeNumber, @RequestParam("isVip") boolean isVip) {
        Map<String, Object> result = new HashMap<>();
        CommodityOrder commodityOrder = productInquiry.queryProduct(codeNumber);
        if (null == commodityOrder) {
            result.put("isSucc", false);
            logger.error("未在超市库查询到商品：" + codeNumber);
            result.put("error", "未在超市库查询到商品，请重新扫码");
            return JSONObject.toJSONString(result);
        }
        Map<String, Object> info = new HashMap<>();
        info.put("barcode", commodityOrder.getBarcode());
        info.put("name", commodityOrder.getProductName());
        long price;
        long discountPrice;
        price = commodityOrder.getPriceA();
        if (isVip) {
            discountPrice = price - commodityOrder.getPriceD();
        } else {
            discountPrice = 0;
        }
        info.put("price", price / 100.0);
        info.put("discountPrice", discountPrice / 100.0);
        info.put("count", 1);
        result.put("isSucc", true);
        result.put("message", info);
        return JSONObject.toJSONString(result);
    }


    /**
     * 扫码查询商品(入库)
     *
     * @param codeNumber 商品码
     * @return
     */
    @GetMapping("queryProductIn")
    @ResponseBody
    @PreAuthorize("hasAuthority('admin:manag')")
    public String queryProductIn(@RequestParam("codeNumber") String codeNumber) {
        Map<String, Object> result = new HashMap<>();
        // 查询信息库中商品
        CommodityLibrary commodityLibrary = productInquiry.queryProductIn(codeNumber);
        if (null == commodityLibrary || commodityLibrary.isEmpty()) {
            result.put("isSucc", false);
            result.put("error", "未在超市库和网络库中查询到商品，请重新扫码");
            return JSONObject.toJSONString(result);
        }
        result.put("isSucc", true);
        // 查询超市库中商品
        CommodityOrder commodity = commodityOrderService.getById(codeNumber);
        if (null != commodity) {
            result.put("message", commodity);
            result.put("productFormDisabled", true);
        } else {
            CommodityOrder commodityOrder = new CommodityOrder();
            commodityOrder.setProductName(commodityLibrary.getItemName());
            commodityOrder.setBarcode(commodityLibrary.getItemNo());
            String pym = commodityLibrary.getPym().replaceAll("￥", "");
            long priceEnd = 0L;
            try {
                double price = Double.parseDouble(pym);
                priceEnd = Math.round(price * 100);
            } catch (Exception e) {
                logger.info("扫码入库中.....");
                logger.error(e.getMessage());
            }
            commodityOrder.setPriceA(priceEnd);
            commodityOrder.setSpec(commodityLibrary.getUnitNo());
            commodityOrder.setOriginCountry(commodityLibrary.getProductArea());
            result.put("message", commodityOrder);
            result.put("productFormDisabled", false);
        }
        return JSONObject.toJSONString(result);
    }

    /**
     * 商品入库或者更新库存
     *
     * @param commodityOrder
     * @return
     */
    @PostMapping("enterProductIn")
    @ResponseBody
    @PreAuthorize("hasAuthority('admin:manag')")
    public String saveProductIn(@RequestBody CommodityOrder commodityOrder) {
        Map<String, Object> result = new HashMap<>();
        if (null == commodityOrder || commodityOrder.isEmpty()) {
            result.put("isSucc", 401);
            result.put("error", "商品信息不合规，请检查");
            return JSONObject.toJSONString(result);
        }
        CommodityOrder oldCommodity = commodityOrderService.getById(commodityOrder.getBarcode());
        if (null == oldCommodity) {
            commodityOrderService.save(commodityOrder);
        } else {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            commodityOrderService.updateReserve(commodityOrder.getBarcode(), commodityOrder.getReserve(), now.format(formatter));
        }
        result.put("isSucc", 200);
        return JSONObject.toJSONString(result);
    }

    /**
     * 更新商品信息
     *
     * @param commodityOrder
     * @return
     */
    @PostMapping("modifyProduct")
    @ResponseBody
    @PreAuthorize("hasAuthority('admin:manag')")
    public String modifyProduct(@RequestBody CommodityOrder commodityOrder) {
        Map<String, Object> result = new HashMap<>();
        if (null == commodityOrder || commodityOrder.isEmpty()) {
            result.put("isSucc", 401);
            result.put("error", "商品信息不合规，请检查");
            return JSONObject.toJSONString(result);
        }
        commodityOrderService.updateProduct(commodityOrder);
        result.put("isSucc", 200);
        return JSONObject.toJSONString(result);
    }

    /**
     * 删除商品信息
     *
     * @param commodityOrder
     * @return
     */
    @PostMapping("removeProduct")
    @ResponseBody
    @PreAuthorize("hasAuthority('admin:manag')")
    public String removeProduct(@RequestBody CommodityOrder commodityOrder) {
        Map<String, Object> result = new HashMap<>();
        if (null == commodityOrder || commodityOrder.isEmpty()) {
            result.put("isSucc", 401);
            result.put("error", "商品信息不合规，请检查");
            return JSONObject.toJSONString(result);
        }
        commodityOrder.setStatus("0");
        commodityOrderService.updateProduct(commodityOrder);
        result.put("isSucc", 200);
        return JSONObject.toJSONString(result);
    }

    /**
     * 查询上新商品
     * @return
     */
    @GetMapping("newProduct")
    @ResponseBody
    public String newProduct(){
        return JSONObject.toJSONString(commodityOrderService.queryNewProduct());
    }

    /**
     * 查询优惠商品
     */
    @GetMapping("queryPreferential")
    @ResponseBody
    public String queryPreferential() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> hotSelling = orderDetailService.queryHotSelling();
        for (Map<String, Object> item : hotSelling) {
            Map<String, Object> resultMap = new HashMap<>();
            String productItem = (String) item.get("product_name");
            long productPrice = commodityOrderService.queryProductPrice(productItem);
            resultMap.put("productName", productItem);
            resultMap.put("productPrice", productPrice);
            result.add(resultMap);
        }
        return JSONObject.toJSONString(result);
    }
}
